package com.an.httptest;

import java.net.URI;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

public class MyHandler extends SimpleChannelInboundHandler<HttpObject>{

	private AtomicInteger count = new AtomicInteger(1);

	// 读取客户端数据
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
		// 判断msg是不是httprequest请求
		if(msg instanceof HttpRequest) {
			System.out.println("pipeline hashcode : " + ctx.pipeline().hashCode() + ",this handler hashcode: " + this.hashCode());
			System.out.println("msg类型： " + msg.getClass());
			System.out.println("客户端地址：" + ctx.channel().remoteAddress());
			
			// 
			HttpRequest httpRequest = (HttpRequest) msg;
			// 获取uri，过滤指定的资源
			URI uri = new URI(httpRequest.uri());
			System.out.println("客户端请求资源：" + uri);
			
			
			// 回复消息给浏览器【HTTP协议】
			ByteBuf byteBuf = Unpooled.copiedBuffer("hello，我是服务器，这是你第【" + count.getAndIncrement() + "】次请求",CharsetUtil.UTF_8);
			
			// 构造H偷偷响应
			FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,byteBuf);
			httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
			httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH,httpResponse.content().readableBytes());
			
			
			// 返回
			ctx.writeAndFlush(httpResponse);
		}
		
		
	}
	
}
